# 360设备事件通知
import requests

from commonTool.http_tool import http_tool
from commonTool.logs.logs_wrapper import LogUtil
from manager import api
from manager.tool.ApiTool import ApiTool as apiTool
from manager.tool.Hmac_Sha256_Base64 import HamcSha256Base64
from manager.tool.api_360_tool import get_common_params, get_auth_header, get_product_device_params

logs = LogUtil()


class DeviceApi:

    @staticmethod
    def api_eventmessage_deviceeventnotify_360(dataKey, dataValue, is_sign=False):
        # 添加 context_type
        api.add_request_context('json')

        # 定义请求数据 构建参数，替换环境变量
        dataValue = apiTool.buildReplaceList(dataValue)
        data = apiTool.buildJsonParam(dataKey, dataValue)

        # 加密
        if is_sign:
            HamcSha256Base64.is_device = True
            HamcSha256Base64(msg=dataValue[0], sign=dataValue[1]).get_signature()
        apiTool.buildRequestLog('360设备事件通知', data)

        # 调用post方法
        return requests.post(url=api.device_host + '/v1/ipc/eventmessage/deviceeventnotify/360', data=data,
                             headers=api.headers)

    @staticmethod
    def api_invoke_service_360(app_key, app_secret, domain, pid, product_key, device_name, identifier, input_data):
        url = domain + "/v1/iot/device/invoke_service?" + get_common_params(app_key, app_secret)

        # 设置请求头
        header_params = get_auth_header(pid)

        # 设置body体
        body_params_map = get_product_device_params(product_key, device_name)
        body_params_map["identifier"] = identifier
        input_data = input_data if input_data else "{}"
        body_params_map["input"] = input_data
        body_params = '&'.join([f"{key}={value}" for key, value in body_params_map.items()]).replace(' ', '')
        try:
            response = http_tool.post(url, header_params, body_params)
            return response
        except Exception as e:
            # 处理异常的代码
            return str(e)
